package com.alticor.amwaychina.weibolib;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.DrawableRes;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.widget.Toast;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.api.*;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.sina.weibo.sdk.utils.Utility;
import com.tbruyelle.rxpermissions2.RxPermissions;
import io.reactivex.functions.Consumer;

import java.io.File;

public class WeiboShareUtil {

    public static void shareWebPage(Activity activity , String title ,
                                    String description ,
                                    @DrawableRes int drawableResLogo,
                                    String actionUrl ,
                                    String defaultText){
        if(!WbSdk.isWbInstall(activity)){
            Toast.makeText(activity,"请安装微博客户端", Toast.LENGTH_SHORT).show();
            return ;
        }
        WbShareHandler shareHandler = new WbShareHandler(activity);
        shareHandler.registerApp();
        WeiboMultiMessage  weiboMultiMessage = getWebpageObj(activity,
                title ,
                description ,
                drawableResLogo,
                actionUrl ,
                defaultText);
        shareHandler.shareMessage(weiboMultiMessage ,true);
    }

    /**
     * 创建多媒体（网页）消息对象。
     *
     * @return 多媒体（网页）消息对象。
     */
    private static  WeiboMultiMessage getWebpageObj(Context context,
                                        String title ,
                                        String description ,
                                        @DrawableRes int drawableResLogo,
                                        String actionUrl ,
                                        String defaultText) {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        if(!TextUtils.isEmpty(title)) {
            mediaObject.title = title;
        }
        if(!TextUtils.isEmpty(description)) {
            mediaObject.description = description;
        }
        if(drawableResLogo != 0) {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), drawableResLogo);
            // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
            mediaObject.setThumbImage(bitmap);
        }
        else{
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.amwayiconweibo);
            // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
            mediaObject.setThumbImage(bitmap);
        }
        mediaObject.actionUrl = actionUrl;
        if(!TextUtils.isEmpty(defaultText)) {
            mediaObject.defaultText = defaultText;
        }
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.mediaObject = mediaObject;
        return weiboMessage;
    }


    /*
    share single image
     */
    public static void shareLocalImage(final Activity activity  , final String title, final String text, final String actionUrl, final String localFilPath){
        if(!WbSdk.isWbInstall(activity)){
            Toast.makeText(activity,"请安装微博客户端", Toast.LENGTH_SHORT).show();
            return ;
        }
        final RxPermissions rxPermissions = new RxPermissions((FragmentActivity)activity);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (granted) { // Always true pre-M
                            File file = new File(localFilPath) ;
                            if(!file.exists()){
                                Toast.makeText(activity,"文件不存在", Toast.LENGTH_SHORT).show();
                                return ;
                            }
                            WbShareHandler shareHandler = new WbShareHandler(activity);
                            shareHandler.registerApp();
                            shareHandler.shareMessage(getMultiImageObject(activity,title,text,actionUrl,localFilPath),true);
                        } else {
                            // Oups permission denied
                            Toast.makeText(activity,"用户没有授予读取外部存储器权限", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    /***
     * s
     * @return
     */
    private static  WeiboMultiMessage getMultiImageObject(Activity activity  ,String title, String text, String actionUrl,String  localFilPath){
        TextObject textObject = new TextObject( ) ;
        textObject.title = title ;
        textObject.text  = text  ;
        textObject.actionUrl = actionUrl;
        MultiImageObject multiImageObject = new MultiImageObject();
        //pathList设置的是本地本件的路径,并且是当前应用可以访问的路径，现在不支持网络路径（多图分享依靠微博最新版本的支持，所以当分享到低版本的微博应用时，多图分享失效
        // 可以通过WbSdk.hasSupportMultiImage 方法判断是否支持多图分享,h5分享微博暂时不支持多图）多图分享接入程序必须有文件读写权限，否则会造成分享失败
//        ArrayList<Uri> pathList = new ArrayList<>();
//        //Uri uri = FileProvider.getUriForFile(activity ,"com.alticor.amwaychina.contentHub.provider" ,new File(localFilPath));
//        Uri uri = Uri.fromFile(new File(localFilPath)) ;
//        Uri uri2 = Uri.fromFile(new File(localFilPath)) ;
//        pathList.add(uri);
//        pathList.add(uri2);
//        multiImageObject.setImageList(pathList);
        ImageObject imageObject = new ImageObject();
        Bitmap  bitmap = BitmapFactory.decodeFile(localFilPath);
        imageObject.setImageObject(bitmap);
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        //weiboMessage.mediaObject =   multiImageObject  ;
        weiboMessage.imageObject = imageObject;
        weiboMessage.textObject = textObject ;
        return weiboMessage;
    }

    /*************************************************
     *
     * @return
     */
    public static void shareVideo(final Activity activity  , final String title, final String text, final String actionUrl, final String localFilPath){
        if(!WbSdk.isWbInstall(activity)){
            Toast.makeText(activity,"请安装微博客户端", Toast.LENGTH_SHORT).show();
            return ;
        }
        final RxPermissions rxPermissions = new RxPermissions((FragmentActivity)activity);
        rxPermissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (granted) { // Always true pre-M
                            File file = new File(localFilPath) ;
                            if(!file.exists()){
                                Toast.makeText(activity,"视频不存在", Toast.LENGTH_SHORT).show();
                                return ;
                            }
                            WbShareHandler shareHandler = new WbShareHandler(activity);
                            shareHandler.registerApp();
                            shareHandler.shareMessage(getVideoObject(title,text,actionUrl,localFilPath),true);
                        } else {
                            // Oups permission denied
                            Toast.makeText(activity,"用户没有授予读取外部存储器权限", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }
    private static  WeiboMultiMessage  getVideoObject(String title, String text, String actionUrl,String file){
        //获取视频
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        VideoSourceObject videoSourceObject = new VideoSourceObject();
        videoSourceObject.videoPath = Uri.fromFile(new File(file));
        weiboMessage.videoSourceObject = videoSourceObject ;
        TextObject textObject = new TextObject();
        textObject.text = text;
        textObject.title = title;
        textObject.actionUrl = actionUrl;
        weiboMessage.textObject = textObject;
        return weiboMessage;
    }

    /**********************************************************
     *
     */
    public static void shareText(Activity activity  , String title, String text , String actionUrl){
        if(!WbSdk.isWbInstall(activity)){
            Toast.makeText(activity,"请安装微博客户端", Toast.LENGTH_SHORT).show();
            return ;
        }
        WbShareHandler shareHandler = new WbShareHandler(activity);
        shareHandler.registerApp();
        shareHandler.shareMessage(geTextObject(title ,text , actionUrl),true);
    }
    private static  WeiboMultiMessage  geTextObject(String title,String text , String actionUrl){
        //获取Text
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        TextObject textObject = new TextObject();
        textObject.text = text+actionUrl;
        textObject.title = title;
        textObject.actionUrl = actionUrl;
        weiboMessage.textObject = textObject;
        return weiboMessage;
    }
}
